package com.landon.id.manager;

import com.landon.id.generator.model.SegmentIdDO;
import com.landon.id.model.entity.CosIdSegmentDO;
import com.landon.id.service.CosIdSegmentService;
import com.landon.id.utils.BizAssertUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author landon
 */
@Service
public class CosIdManager {

    @Resource
    private CosIdSegmentService cosIdSegmentService;

    @Transactional(rollbackFor = Exception.class)
    public SegmentIdDO getSegment(String businessId, Long segmentCount) {
        // 获取号段
        CosIdSegmentDO cosIdSegment = this.initBusinessSegment(businessId);
        Boolean result = cosIdSegmentService.getBaseMapper().updateCosIdSegmentAutoIncrement(cosIdSegment.getId(), segmentCount);
        BizAssertUtil.isTrue(result, "获取号段异常");
        cosIdSegment = cosIdSegmentService.getById(cosIdSegment.getId());
        return new SegmentIdDO()
                .setStartId(cosIdSegment.getAutoIncrement() - segmentCount)
                .setEndId(cosIdSegment.getAutoIncrement())
                .setBusinessId(businessId);
    }

    public CosIdSegmentDO initBusinessSegment(String businessId) {
        return cosIdSegmentService.saveOrUpdate(businessId);
    }
}
